﻿using AntJoin.Core.Configuration;
using AntJoin.Core.Security;
using AntJoin.Core.Utils;
using Microsoft.Extensions.Configuration;
using System;

namespace AntJoin.Redis
{
    public class RedisConfig
    {
        #region Host
        /// <summary>
        /// Host
        /// </summary>
        public string Host { get; set; }
        #endregion

        #region Port
        /// <summary>
        /// Port
        /// </summary>
        public int Port { get; set; }
        #endregion

        #region Password
        /// <summary>
        /// Password
        /// </summary>
        public string Password { get; set; }
        #endregion
        public int DbName { get; set; }

        public RedisConfig(string configName = "RedisConnectionStrings")
        {
            int portDefault = 6379;
            string hostDefault = "127.0.0.1";
            string redisConnStr = ConfigurationHelper.GetValue(configName);
            dynamic config = JsonHelper.DeserializeJsonToDynamic(redisConnStr);
            string redisIp = config.RedisIp;
            int redisPort = config.RedisPort;
            string redisPassword = config.RedisPassword;
            int redisDb = config.RedisDb;
            //获取IP
            if (!string.IsNullOrWhiteSpace(redisIp))
            {
                Host = redisIp;
            }
            else
            {
                Host = hostDefault;
            }
            //获取端口号
            if (redisPort != 0)
            {
                Port = redisPort;
            }
            else
            {
                Port = portDefault;
            }
            DbName = redisDb;
            //密码
            if (!string.IsNullOrWhiteSpace(redisPassword))
            {
                if (string.Equals(redisPassword, "OhIoC3Vr"))
                {
                    Password = redisPassword;
                }
                else
                {
                    Password = AJSecurity.AJDecrypt(redisPassword);
                }
            }
            else
            {
                Password = "";
            }
        }
    }
}
